package com.tf_cut.backend.util;

import com.tf_cut.backend.agent.vo.AgentCashOrderVo;
import com.tf_cut.backend.mapper.AgentCashMapper;
import com.tf_cut.backend.mapper.GrantDetailMapper;
import com.tf_cut.backend.platform.vo.GrantDetailVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;

@Component
public class OrderPaymentQueue {
    private static Logger logger = LogManager.getLogger(OrderPaymentQueue.class);

    @Resource
    private GrantDetailMapper grantDetailMapper;
    @Resource
    private AgentCashMapper agentCashMapper;

    private OrderPaymentQueue orderPaymentQueue;

    private static ArrayBlockingQueue<Object> orders = new ArrayBlockingQueue<Object>(10000);

    @PostConstruct
    public void init() {
        orderPaymentQueue = this;
        orderPaymentQueue.orders = this.orders;

        logger.info("初始化第三方支付订单付款队列...");
        logger.info("正在查询发放明细记录：");
        List<GrantDetailVo> details = grantDetailMapper.queryAllPaymentOrder("O");

        Set<String> orderIds = new HashSet<String>();

        for(GrantDetailVo detailVo : details){
            orderIds.add(detailVo.getOrderId());
        }

        logger.info("查询发放明细记录完毕，共"+details.size()+"条明细记录待发往第三方支付请求付款！");

        for(String str : orderIds){
            try {
                orders.put(str);
            } catch (InterruptedException e) {
                logger.error("存放队列失败：",e);
            }
        }

        logger.info("正在查询提现记录：");
        List<AgentCashOrderVo> cashOrderVos = agentCashMapper.queryAllPaymentOrder("O");

        for(AgentCashOrderVo cashOrderVo : cashOrderVos){
            try {
                orders.put(cashOrderVo);
            } catch (InterruptedException e) {
                logger.error("存放队列失败：",e);
            }
        }

        logger.info("查询提现记录完毕，共"+cashOrderVos.size()+"条明细记录待发往第三方支付请求付款！");
        logger.info("第三方支付订单付款队列初始化完毕，共计" + orders.size() + "条记录.");
    }

    public static Object get(){
        try {
            return orders.take();
        } catch (InterruptedException e) {
            logger.error("获取队列中数据失败：",e);
            return null;
        }
    }

    public static void set(Object order){
        try {
            orders.put(order);
        } catch (InterruptedException e) {
            logger.error("存储队列失败：",e);
        }
    }

    public static int size(){
        return orders.size();
    }
}
